<template>
  <div>
    <el-upload
      :before-upload="beforeUpload"
      action="#"
      :http-request="handleRequest"
      list-type="picture-card"
      :on-remove="handleRemove"
      :on-preview="handlePreview"
      :file-list="fileList"
      :limit="limit"
      :class="{disabled:fileNumber}"
      :on-change="handleChange"
    >
      <i class="el-icon-plus" />
    </el-upload>

    <!-- 图片预览的弹出框 -->
    <el-dialog title="图片预览" :visible.sync="showDialog">
      <img :src="imgSrc" alt="" style="width:100%">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDgBSTFo7BzYruiGZcQ0LQFpAG6h290cz7', // 身份识别ID
  SecretKey: 'udIrDJAm9GCsISN2SebJmzxf7KHyQcYE' // 身份秘钥
})

export default {
  name: 'ImageUpload',
  props: {
    limit: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      fileList: [],
      imgSrc: '',
      showDialog: false
    }
  },
  computed: {
    fileNumber() {
      return this.fileList.length >= this.limit
    },
    fileSuccess() {
      return this.fileList.every(item => item.status === 'success')
    }
  },
  methods: {
    // 图片预览
    handlePreview(file) {
      this.imgSrc = file.url
      this.showDialog = true
    },
    handleRemove(file, fileList) {
      // file是删除的文件
      // file:页面结构上图片数据
      // this.fileList: 数据层的图片数据
      this.fileList = [...fileList]
    },
    handleChange(file, fileList) {
      console.log(file, fileList)
      this.fileList = [...fileList]
    },
    // 配置上传前的校验, 只要通过校验, 才能进行上传
    beforeUpload(file) {
      // 1. 限制文件类型 file.type
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (!types.includes(file.type)) {
        this.$message.error('上传的图片格式, 必须是jpg, gif, bmp, png的格式!')
        return false
      }
      // 2. 限制文件大小 file.size
      if (file.size / 1024 / 1024 >= 5) {
        this.$message.error('上传头像过大, 超过了5M, 必须5M以内')
        return false
      }
      return true
    },
    handleRequest(obj) {
      const fileObj = this.fileList.find(item => item.uid === obj.file.uid)
      fileObj.status = 'uploading'
      // 图片上传到服务器
      cos.putObject({
        Bucket: 'hrsass-74-1312329431', /* 存储桶 */
        Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
        Key: parseInt(Math.random() * 10000) + obj.file.name, /* 文件名 */
        StorageClass: 'STANDARD', // 上传模式, 标准模式
        Body: obj.file, // 上传文件对象
        onProgress: (progressData) => {
          fileObj.percentage = parseInt(progressData.percent * 100)
        }
      }, (err, data) => {
        if (err) return

        // 更新状态
        fileObj.status = 'success'
        // 修改地址
        fileObj.url = 'https://' + data.Location
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.disabled {
  ::v-deep {
    .el-upload--picture-card {
      display: none
    }
  }
}
</style>
